﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VirtualPress.Portal.WebLogic;
using VirtualPress.Portal.WebLogic.Authentication;
using VirtualPress.Infrastructure.Entities.Enum;
using VirtualPress.Infrastructure.Entities.Entity;
using System.Linq.Expressions;
using VirtualPress.Infrastructure.Entities.Repository;
using VirtualPress.Portal.Biz;
using VirtualPress.Portal.Web.Areas.WorkSpace.Models;
using VirtualPress.Tool.Framework;
using System.IO;

namespace VirtualPress.Portal.Web.Areas.WorkSpace.Controllers
{
#if !DEBUG
    [ErrorHandle]
#endif
    [Auth(UserRole.ConferenceAdmin, UserRole.Admin)]
    [WorkSpace(UserRole.ConferenceAdmin)]
    public class MeetingController : Controller
    {
        public ActionResult Index()
        {
            Meeting data = ViewBag.Meeting;
            if (!data.isInstall)
            {
                return RedirectToAction("Install");
            }
            ViewBag.ArticleCount = new Article().Count(c => c.Conference_Id == data.Id && !c.IsDelete);
            var container = new List<int>() { 0, 2, 4, 6, 8, 10 };
            var waitArticle = new Article().FindAll(
                c => c.Conference_Id == data.Id && container.Contains(c.Status) && !c.IsDelete,
                c => c.Id, 0, 5);
            ViewBag.WaitProccess = waitArticle;
            var counsellor = MeetingBiz.GetAllLeaguer(data.Id, 0, 5);
            if (counsellor != null)
            {
                counsellor.ForEach(c =>
                {
                    c.LoadUser(new User().Find(c.UserName), new Expert().Find(c.UserName));
                });
            }
            ViewBag.Counsellor = counsellor;
            return View();
        }
        public ActionResult Install()
        {
            var meeting = ViewBag.Meeting;
            if (meeting.isInstall)
            {
                return RedirectToAction("Index");
            }
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult install(int meeting, string Password,string Email,
            string ContactInfo,string Address,string Fax,string ZBDW,string CBDW,string StartDate,
            string ArticleEndDate, string HYGM,string Abstract,string CallForPaper,string Attention,
            string ZGFW,string Schedule, string Travel, string About, string Committee,string AboutUs,
            int DefaultExamineDay, int ManuscriptPageSize, bool isFeeForExpertExmaine, int PricePerPrice, 
            int PublicationPrice, int PagePrice = 0)
        {
            Meeting meetingEntity = ViewBag.Meeting;
            if (meetingEntity == null || meetingEntity.isInstall)
            {
                return RedirectToAction("Index");
            }
            var user = new User().Find(HttpContext.User.Identity.Name);
            user.Password = VirtualPress.Tool.Framework.AesAlgorithm.Encrypt(Password);
            user.PostModify();
            meetingEntity.Email = Email;
            meetingEntity.isInstall = true;
            meetingEntity.ContactInfo = ContactInfo.Replace("\r\n","<br/>");
            meetingEntity.Address = Address;
            meetingEntity.About = About;
            meetingEntity.Committee = Committee;
            meetingEntity.AboutUs = AboutUs;
            meetingEntity.Fax = Fax;
            meetingEntity.ZBDW = ZBDW;
            meetingEntity.CBDW = CBDW;
            meetingEntity.StartDate = DateTime.Parse(StartDate);
            meetingEntity.ArticleEndDate = DateTime.Parse(ArticleEndDate);
            meetingEntity.HYGM = HYGM;
            meetingEntity.Abstract = Abstract;
            meetingEntity.CallForPaper = CallForPaper;
            meetingEntity.Attention = Attention;
            meetingEntity.ZGFW = ZGFW.Replace("\r\n", "");
            meetingEntity.Schedule = Schedule.Replace("\r\n", "<br/>");
            meetingEntity.Travel=Travel;
            meetingEntity.DefaultExamineDay=DefaultExamineDay;
            meetingEntity.ManuscriptPageSize=ManuscriptPageSize;
            meetingEntity.isFeeForExpertExmaine = isFeeForExpertExmaine;
            meetingEntity.PricePerPrice=PricePerPrice;
            meetingEntity.PublicationPrice = PublicationPrice;
            meetingEntity.PagePrice = PagePrice;

            new ImportantPan()
            {
                CreateDate = DateTime.Now,
                meetingId = meetingEntity.Id,
                PanDate = DateTime.Parse(StartDate),
                Title = String.Format("会议于{0}举办", StartDate)
            }.PostAdd();
            new ImportantPan()
            {
                CreateDate = DateTime.Now,
                meetingId = meetingEntity.Id,
                PanDate = DateTime.Parse(ArticleEndDate),
                Title = String.Format("会议于{0}截稿", ArticleEndDate)
            }.PostAdd();
            if (meetingEntity.PostModify() == null)
            {
                LogHelper.Write(CommonLogger.Journal, LogLevel.Error, meeting + " install 失败");
            }
            return RedirectToAction("Index");
        }
        #region 稿件中心
        /// <summary>
        /// 
        /// </summary>
        /// <param name="meeting"></param>
        /// <param name="group">
        /// 0：最新稿件 （type= 0）
        /// 1：待分配稿件（type= 专审待分配:2; 专审完成:4; 专审修订完成:6; 终审完成:8; 终审修订完成:10）
        /// 2：专审稿件(type= 专审中:3; 专审修订:5)
        /// 3：终审稿件(type= 终审中:7; 终审修订:9)
        /// 4：录用稿件(type= 录用已缴费:30; 已出版:40)
        /// 5：拒绝稿件(type= 废弃:99)
        /// 6：待缴费稿件(type= 专审待缴费:1; 录用:20; 补交费:80)
        /// 9：全部稿件
        /// </param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Article(int meeting = -1, int group = 0, int page = 0)
        {
            var groupmap = new
            {
                最新 = new List<int>() { 0 },
                待分配 = new List<int>() { 2, 4, 6, 8, 10 },
                专审 = new List<int>() { 3, 5 },
                终审 = new List<int>() { 7, 9 },
                录用 = new List<int>() { 30, 40 },
                拒绝 = new List<int>() { 99 },
                缴费 = new List<int>() { 1, 20, 80 }
            };
            Meeting entity = ViewBag.Meeting;
            Expression<Func<T_Article, bool>> where = null;
            if (group == 9)
            {
                where = c => c.Conference_Id == entity.Id && !c.IsDelete;
            }
            else
            {
                List<int> contain = new List<int>();
                switch (group)
                {
                    default:
                    case 0:
                        contain = groupmap.最新;
                        break;
                    case 1:
                        contain = groupmap.待分配;
                        break;
                    case 2:
                        contain = groupmap.专审;
                        break;
                    case 3:
                        contain = groupmap.终审;
                        break;
                    case 4:
                        contain = groupmap.录用;
                        break;
                    case 5:
                        contain = groupmap.拒绝;
                        break;
                    case 6:
                        contain = groupmap.缴费;
                        break;
                }
                where = c => c.Conference_Id == entity.Id && contain.Contains(c.Status) && !c.IsDelete;
            }
            List<Article> list = MeetingBiz.GetAllArticle(where, group == 2, page, 20);
            var data = new ItemListBox<Article>(list).BuildPage(
                MeetingBiz.GetAllArticleForPage(where),
                page, 20,
                new PageParameter()
                {
                    IsActive = false,
                    Param_page = "page",
                    Style = "workspace"
                });
            ViewBag.Article = data;
            ViewBag.Group = group;
            return View();
        }
        [SelfArticle("id")]
        public ActionResult ArticleDetail(int id)
        {
            var article = new Article().Find(c => c.Id == id);
            var author = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            var meeting = new Meeting().Find(article.Conference_Id.ToString());
            //作者信息
            ViewBag.ArticleAuthor = author;
            //稿件
            ViewBag.Article = article;
            //期刊
            ViewBag.Meeting = meeting;
            //附件
            ViewBag.Attachment = new Appendix().FindAll(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
            //稿件历史
            ViewBag.History = MeetingBiz.GetAllArticleHistory(article.Id);
            //审稿记录
            var records = MeetingBiz.GetAllAuditingRecord(article.Id); ;
            ViewBag.AuditingRecord = records;
            var ExpertList = MeetingBiz.FindExpertForExamine(meeting, article,
                records.Where(c => c.Step != ExamineStep.ChuShen)
                       .Select(c => c.UserName).ToList());
            ViewBag.ExpertList = ExpertList;
            return View();
        }
        public ActionResult NewManuscriptCheck(int id, int meeting = -1)
        {
            Meeting entity = ViewBag.Meeting;
            var article = new Article().Find(id.ToString());
            if (article.Conference_Id != entity.Id)
            {
                return Redirect(String.Format("/workspace/meeting/index{0}", meeting >= 0 ? "?meeting=" + meeting : ""));
            }
            ViewBag.Article = article;
            var articleAuthor = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            ViewBag.Authors = articleAuthor;
            ViewBag.Attachment = new Appendix().FindAll(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewManuscriptCheck(int id, bool optionsRadios, string RefuseMessage, int Page = 0, int meeting = -1)
        {
            Meeting entity = null;
            if (meeting != -1)
            {
                entity = new Meeting().Find(meeting.ToString());
            }
            else
            {
                entity = new Meeting().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }
            if (entity == null)
            {
                return Redirect(String.Format("/workspace/Meeting/index{0}", meeting >= 0 ? "?meeting=" + meeting : ""));
            }
            Article article = new Article().Find(id.ToString());
            if (article == null)
            {
                return Redirect(String.Format("/workspace/meeting/index{0}", meeting >= 0 ? "?meeting=" + meeting : ""));
            }
            if (MeetingBiz.DoManuscriptCheck(article, Page, optionsRadios, RefuseMessage.NoHTMLLabel("script")))
            {
                return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=newmanuscriptcheck&s={0}{1}", optionsRadios ? "1" : "0", "&meeting=" + meeting));
            }
            return Redirect("/workspace/meeting/article?group=0");
            
        }
        public ActionResult ConfirmIsPay(int id)
        {
            var article = new Article().Find(id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (article != null && user != null)
            {
                var meeting = new Meeting().Find(article.Conference_Id.ToString());
                if (meeting != null)
                {
                    if (meeting.Admin.ToLower() == HttpContext.User.Identity.Name.ToLower() ||
                        user.SystemRole == UserRole.Admin)
                    {
                        var articleHistory = new ArticleHistory()
                        {
                            CreateTime = DateTime.Now,
                            PreStatus = article.Status,
                            ManuscriptId = article.Id,
                            Message = "管理员确认缴费",
                            Operator = HttpContext.User.Identity.Name
                        };

                        if (article.Status == ArticleStatus.ZhuanShenDaiJiaoFei)
                        {
                            article.Status = ArticleStatus.ZhuanShenDaiFenPei;
                            article.PostModify();

                            articleHistory.CurrentStatus = ArticleStatus.ZhuanShenDaiFenPei;
                        }
                        else if (article.Status == ArticleStatus.LuYong)
                        {
                            article.Status = ArticleStatus.ChuBanYiJiaoFei;
                            article.PostModify();

                            articleHistory.CurrentStatus = ArticleStatus.ChuBanYiJiaoFei;
                        }
                        else if (article.Status == ArticleStatus.BuJiaoFei)
                        {
                            article.Status = ArticleStatus.ZhuanShenDaiFenPei;
                            article.PostModify();

                            articleHistory.CurrentStatus = ArticleStatus.ZhuanShenDaiFenPei;
                        }
                        articleHistory.PostAdd();

                        var bill = new Reckoning().Find(c => c.PayFor == 0 && c.RaletionId == article.Id && c.Status == 0);
                        if (bill != null)
                        {
                            bill.Status = BillStatus.ZhiFuWanCheng;
                            bill.PayType = PayType.Offline;
                            bill.PostModify();
                        }
                    }
                }
            }
            return RedirectToAction("Article", new { group = 6 });
        }
        public ActionResult CancelArticle(int id, int group = 0)
        {
            MeetingBiz.CancelArticleForMeeting(id);
            return RedirectToAction("Article", new { group = group });
        }/// <summary>
        /// 专审分配
        /// </summary>
        /// <param name="id"></param>
        /// <param name="meeting"></param>
        /// <returns></returns>
        public ActionResult Distribution(int id, int meeting = -1)
        {
            Meeting entity = ViewBag.Meeting;
            var article = new Article().Find(id.ToString());
            if (article == null)
            {
                return Redirect(String.Format("/workspace/home/index{0}", meeting >= 0 ? "?meeting=" + meeting : ""));
            }
            var ExpertList = MeetingBiz.FindExpertForExamine(entity, article, null);
            ViewBag.Article = article;
            ViewBag.ExpertList = ExpertList;
            var authors = new ArticleAuthor().FindAll(
                c => c.ManuscriptId == article.Id);
            ViewBag.Author = authors;
            var attachment = new Appendix().FindAll(
                c => c.Type == 1 && c.RaletionId == article.Id);
            ViewBag.Attachment = attachment;
            return View();
        }
        [HttpPost]
        public ActionResult Distribution(int articleId, int finishDate, string experts)
        {
            MeetingBiz.DoDistribution(articleId, DateTime.Now.AddDays(finishDate), experts);
            return RedirectToAction("article", new { group = 1 });
        }
        public ActionResult Examineresult(int id, int meeting = -1)
        {
            AuditingRecord record = new AuditingRecord().Find(id.ToString());
            Meeting entity = ViewBag.Meeting;
            Article article = new Article().Find(record.ManuscriptId.ToString());
            ViewBag.Authors = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            ViewBag.Record = record;
            ViewBag.Article = article;

            if (record.AppendixId > 0)
            {
                ViewBag.Attachment = new Appendix().Find(record.AppendixId.ToString());
            }
            return View();
        }
        /// <summary>
        /// 专审验收
        /// </summary>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public ActionResult CheckAndAcceptance(int articleId)
        {
            ViewBag.Article = new Article().Find(articleId.ToString());
            ViewBag.Authors = new ArticleAuthor().FindAll(c => c.ManuscriptId == articleId);
            ViewBag.Records = MeetingBiz.GetAllAuditingRecord(articleId, c => c.ExamineStatus == (int)ExamineStatus.WanCheng &&
                c.ManuscriptId == articleId && c.Step == (int)ExamineStep.ZhuanShen);
            return View();
        }
        public ActionResult CancelExamine(int id, int articleId)
        {
            MeetingBiz.CancelExamineForArticle(id);
            return RedirectToAction("articledetail", new { id = articleId });
        }
        public void UrgeExamine(int id)
        {
            MeetingBiz.urgeExamine(id);
        }
        public void AppendExamineExpert(int articleId, string expert, int finishDate)
        {
            MeetingBiz.AppendExamineExpert(articleId, expert, DateTime.Now.AddDays(finishDate));
        }
        /// <summary>
        /// 专审完成，验收
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public ActionResult acceptanceexamine(int articleId, int result, string msg, string sheetids)
        {
            Meeting meeting = ViewBag.Meeting;
            int[] recordsId = null;
            if (!String.IsNullOrEmpty(sheetids))
            {
                recordsId = sheetids.Split(';').Where(c => !String.IsNullOrEmpty(c)).Select(c => Int32.Parse(c)).ToArray();
            }
            int res = MeetingBiz.AcceptanceExamine(articleId, result, msg.NoHTMLLabel("script"), recordsId);
            if (res == 2)
            {
                var article = new Article().Find(articleId.ToString());
                return RedirectToAction("distribution", new { id = articleId, meeting = meeting.Id });
            }
            return Redirect("/workspace/meeting/article?group=1");
        }
        public ActionResult conclusiveexamine(int articleId, int totalPay, int result, string msg)
        {
            bool success = MeetingBiz.ConclusiveExamine(articleId, totalPay, result, msg);
            return Redirect("/workspace/meeting/article?group=3");
        }
        [HttpPost]
        public ActionResult OverExamie(int articleId)
        {
            MeetingBiz.OverExamie(articleId, "Article");
            return RedirectToAction("ArticleBank");
        }
        #endregion

        #region 稿件出版
        public ActionResult ArticleBank(int meeting = -1, int page = 0)
        {
            Meeting entity = ViewBag.Meeting;
            Expression<Func<T_Article, bool>> where = c => c.Conference_Id == entity.Id && c.Status == (int)ArticleStatus.DaiChuBan && !c.IsDelete;
            List<Article> list = MeetingBiz.GetAllArticle(where, false, page, 20);
            var data = new ItemListBox<Article>(list).BuildPage(
                JournalBiz.GetAllArticleForPage(where),
                page, 20,
                new PageParameter()
                {
                    IsActive = false,
                    Param_page = "page",
                    Style = "workspace"
                });
            ViewBag.Article = data;
            return View();
        }
        /// <summary>
        /// 手工添加稿件
        /// </summary>
        /// <returns></returns>
        public ActionResult manualArticle()
        {
            var author = new Author().FindAll(c => c.UserName == HttpContext.User.Identity.Name);
            ViewBag.Author = author;
            return View();
        }
        [HttpPost]
        public ActionResult manualArticle(ContributeModel model)
        {
            if (!MeetingBiz.ManualArticle(new Article()
            {
                ArticleType = Infrastructure.Entities.Enum.ArticleType.Journal,
                Abstract = model.Abstract.Replace("\r\n", "<br/>"),
                Abstract_EN = model.Abstract_EN.Replace("\r\n", "<br/>"),
                CreateTime = DateTime.Now,
                KeyWords = model.KeyWords,
                KeyWords_EN = model.KeyWords_EN,
                Conference_Id=model.meetingId,
                Status = ArticleStatus.DaiChuBan,
                Title = model.Title,
                Title_EN = model.Title_EN,
                UserName = HttpContext.User.Identity.Name,
                SubmitTime = DateTime.Now,
                IsDelete = false,
                GJFW = String.IsNullOrEmpty(model.GJFW) ? "" : (model.GJFW.EndsWith(";") ? model.GJFW.Remove(model.GJFW.Length - 1) : model.GJFW)
            }, model.Author.Split(';').ToList()))
            {
                RedirectToAction("articlebank");
            }

            //发送审核邮件
            return RedirectToAction("articlebank");
        }
        public ActionResult Catalog()
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Catalog(int id, string catalog)
        {
            Meeting meeting = ViewBag.Meeting;
            meeting.Catalog = catalog;
            meeting.PostModify();
            return Redirect("/WorkSpace/Home/ServerMessage?c=meeting&a=catalog&s=1");
        }
        #endregion

        #region 会议管理
        /// <summary>
        /// 编委会
        /// </summary>
        /// <param name="meeting"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Counsellor(int meeting = -1, int page = 0)
        {
            Meeting entity = ViewBag.Meeting;
            var editorial = MeetingBiz.GetAllLeaguer(entity.Id, page, 20);
            ItemListBox<Organization> list = new ItemListBox<Organization>(editorial);
            list.BuildPage(MeetingBiz.GetAllLeaguerForPage(entity.Id), page, 20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });

            ViewBag.Editorial = list;
            return View();
        }
        /// <summary>
        /// 移除管委会成员
        /// </summary>
        /// <param name="u"></param>
        /// <param name="meeting"></param>
        /// <returns></returns>
        public ActionResult CacnelEditorial(string u, int meeting = -1)
        {
            Meeting entity = ViewBag.Meeting;
            MeetingBiz.CancelEditorial(entity.Id, u);
            return RedirectToAction("Counsellor");
        }
        public ActionResult InvitePending(int meeting = -1, int page = 0)
        {
            Meeting entity = ViewBag.Meeting;
            var editorial = MeetingBiz.GetAllPendingMember(entity.Id, page, 20);
            ItemListBox<Organization> list = new ItemListBox<Organization>(editorial);
            list.BuildPage(MeetingBiz.GetAllLeaguerForPage(entity.Id), page, 20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });

            ViewBag.Editorial = list;
            return View();
        }
        public void ReMailToInviteExpert(string u, int meeting = -1)
        {
            Meeting data = ViewBag.Meeting;
            MeetingBiz.ReMailToInviteExpert(u, data.Id);
        } 
        /// <summary>
        /// 添加编委会
        /// </summary>
        /// <param name="meeting"></param>
        /// <returns></returns>
        public ActionResult InviteCounsellor(int meeting = -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult InviteCounsellor(string ExpertAccount, int meeting = -1)
        {
            Meeting meetingEntity = ViewBag.Meeting;
            if (new Organization().Any(c => c.OrgId == meetingEntity.Id && c.OrgType == (int)OrganizationType.Meeting && c.Status == (int)JournalStatus.Counsellor
                && c.ApplyStatus == 1 && c.UserName == ExpertAccount))
            {
                //如果已经存在
                ViewBag.Exist = true;
                ViewBag.Account = ExpertAccount;
                ViewBag.Expert = null;
                return View();
            }
            User user = new User().Find(ExpertAccount);
            ViewBag.Account = ExpertAccount;
            ViewBag.Expert = user;
            ViewBag.Exist = false;
            return View();
        }
        public ActionResult MailToInvite(string u = "", int meeting = -1, int i = 0)
        {
            ViewBag.Account = u;
            return View();
        }
        /// <summary>
        /// 邀请站外专家加入编委会
        /// </summary>
        /// <param name="ExpertAccount"></param>
        /// <param name="meeting"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MailToInvite(string ExpertAccount, int meeting = -1)
        {
            Meeting entity = null;
            if (meeting != -1)
            {
                entity = new Meeting().Find(meeting.ToString());
            }
            else
            {
                entity = new Meeting().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }

            int result = MeetingBiz.MailToInviteForExpert(ExpertAccount, entity.Id);
            if (result == 1)
            {
                return Redirect("/WorkSpace/Home/ServerMessage?c=meeting&a=mailtoinvite&s=1");
            }
            else if (result == 2)
            {
                ViewBag.Message = "该专家账号已在平台注册存在，您可以通过从现有专家库添加来邀请他（她）加入编委会";
            }
            else
            {
                ViewBag.Message = "该账号已在平台注册存在，但并不是专家账号。如有疑问请联系管理员协助解决";
            } return View();
        }
        /// <summary>
        /// 邀请站内专家加入编委会
        /// </summary>
        /// <param name="ExpertAccount"></param>
        /// <param name="meeting"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DoInvite(string ExpertAccount, int meeting = -1)
        {
            Meeting entity = null;
            if (meeting != -1)
            {
                entity = new Meeting().Find(meeting.ToString());
            }
            else
            {
                entity = new Meeting().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }

            if (MeetingBiz.DoInviteForExpert(ExpertAccount, entity.Id))
            {
                return Redirect("/WorkSpace/Home/ServerMessage?c=meeting&a=doinvite&s=1");
            }
            else
            {
                return Redirect("/WorkSpace/Home/ServerMessage?c=meeting&a=doinvite&s=0");
            }
        }
        public ActionResult author(int page=0)
        {
            var authors = UserBiz.GetAllAuthor(HttpContext.User.Identity.Name, page, 20);
            ViewBag.Author = new ItemListBox<Author>(authors)
                .BuildPage(UserBiz.GetAllAuthorForPage(HttpContext.User.Identity.Name),
                page, 20,
                new PageParameter() { 
                    Style="workspace"
                });
            return View();
        }
        public ActionResult CancelAuthor(int id)
        {
            var author = new Author().Find(c => c.Id == id && c.UserName == HttpContext.User.Identity.Name);
            if (author != null)
            {
                author.PostDelete();
            }
            return RedirectToAction("Author");
        }
        public ActionResult authorinfo()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult authorinfo(NewAuthorModel model)
        {
            UserBiz.SaveNewAuthor(new Author()
            {
                Address = model.Address,
                CreateTime = DateTime.Now,
                Degree = model.Degree,
                Department = model.Department,
                Department_EN = model.Department_EN,
                Email = model.Email,
                FirstName = model.FirstName,
                Gender = (Gender)model.Gender,
                Introduction = model.Introduction,
                Introduction_EN = model.Introduction_EN,
                LastName = model.LastName,
                PostCode = model.PostCode,
                Title = model.Title,
                Title_EN = model.Title_EN,
                UserName = HttpContext.User.Identity.Name,
                Phone = model.Phone
            });
            return RedirectToAction("Author");
        }
        public ActionResult BaseInfo(int meeting = -1)
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult BaseInfoEdit(int Id, NewMeetingModel model)
        {
            var meeting = new Meeting().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (meeting != null)
            {
                var file = System.Web.HttpContext.Current.Request.Files["CoverImg"];
                if (file != null && file.ContentLength > 0)
                {
                    string basedir = "/content/meeting/" + meeting.Name + "/coverimage/";
                    if (!System.IO.Directory.Exists(HttpContext.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Server.MapPath(basedir));
                    }
                    var fileinfo = new FileInfo(file.FileName);
                    string filePath = basedir + meeting.Name + "-converimage" + fileinfo.Extension;
                    file.SaveAs(HttpContext.Server.MapPath(filePath));
                    meeting.Logo = filePath;
                }
                meeting.IndType = (Profession)model.IndType;
                meeting.Email = model.Email;
                meeting.Fax = model.Fax;
                meeting.CBDW = model.CBDW;
                meeting.ContactInfo = model.ContactInfo;
                meeting.HYGM = model.HYGM;
                meeting.Address = model.Address;
                meeting.ZGFW = model.ZGFW.Replace("\r\n", "");
                meeting.StartDate = DateTime.Parse(model.StartDate);
                meeting.ArticleEndDate = DateTime.Parse(model.ArticleEndDate);
                meeting.Schedule = model.Schedule;
                meeting.Travel = model.Travel;

                if (meeting.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=baseinfoedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=baseinfoedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        
        public ActionResult Links(int journal = -1, int page = 0)
        {
            Meeting meeting = ViewBag.Meeting;
            var list = new ItemListBox<FriendLink>(MeetingBiz.GetAllLinks(c => c.RelationId == meeting.Id && c.RelationType==2, page, 20));
            list.BuildPage(JournalBiz.GetAllLinksForPage(c => c.RelationId == meeting.Id && c.RelationType == 2),
                page,
                20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });
            ViewBag.Links = list;
            return View();
        }
        public ActionResult AddLinks(int journal = -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddLinks(int Id, string Title, string URL, string Remark)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            FriendLink item = MeetingBiz.SaveNewFriendLink(new FriendLink()
            {
                CreateTime = DateTime.Now,
                RelationId = Id,
                RelationType= 2,
                Remark = Remark,
                Title = Title,
                URL = URL
            });
            return Redirect("/workSpace/meeting/links");
        }
        public ActionResult LinkCancel(int Id, int journal = -1)
        {
            FriendLink link = new FriendLink().Find(Id.ToString());// JournalBiz.GetLink(Id);
            if (link != null)
            {
                link.PostDelete();
            }
            return Redirect(String.Format("/WorkSpace/meeting/Links{0}", journal >= 0 ? "?journal=" + journal : ""));
        }
        public ActionResult LinkEdit(int Id, int journal = -1)
        {
            FriendLink item = MeetingBiz.GetLink(Id);
            ViewBag.Link = item;
            return View();
        }
        [HttpPost]
        public ActionResult LinkEdit(int Id, string Title, string URL, string Remark)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            FriendLink data = MeetingBiz.GetLink(Id);
            if (data != null)
            {
                data.Title = Title;
                data.URL = URL;
                data.Remark = Remark;
                data.PostModify();
            }
            return Redirect("/workSpace/meeting/links");
        }
        public ActionResult Settings(int meeting = -1)
        {
            return View();
        }
        [HttpPost]
        public ActionResult Settings(string Path, int DefaultExamineDay, int ManuscriptPageSize,
            bool isFeeForExpertExmaine, int PricePerPrice, int PublicationPrice, int PagePrice = 0, int meeting = -1)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            Meeting entity = null;
            if (meeting != -1)
            {
                entity = new Meeting().Find(meeting.ToString());
            }
            else
            {
                entity = new Meeting().Find(c => c.Admin == HttpContext.User.Identity.Name);
            }

            entity.DefaultExamineDay = DefaultExamineDay;
            entity.ManuscriptPageSize = ManuscriptPageSize;
            entity.isFeeForExpertExmaine = isFeeForExpertExmaine;
            entity.PagePrice = PagePrice;
            entity.PricePerPrice = PricePerPrice;
            entity.PublicationPrice = PublicationPrice;
            if (entity.PostModify() != null)
            {
                return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=settings&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + meeting : ""));
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=settings&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + meeting : ""));
        }
        public ActionResult Introduction(int meeting = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult IntrodutionEdit(int Id, string Abstract,string About)
        {
            var meeting = new Meeting().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (meeting != null)
            {
                meeting.Abstract = Abstract.NoHTMLLabel("script");
                meeting.About = About.NoHTMLLabel("script");
                if (meeting.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=introdutionedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=introdutionedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult ContactUs(int meeting = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult ContactUsEdit(int Id, string Committee, string AboutUs)
        {
            var meeting = new Meeting().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (meeting != null)
            {
                meeting.Committee = Committee.NoHTMLLabel("script");
                meeting.AboutUs = AboutUs.NoHTMLLabel("script");
                if (meeting.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=contactus&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=contactus&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Announcement(int meeting = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AnnouncementEdit(int Id, string Announcement)
        {
            var meeting = new Meeting().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (meeting != null)
            {
                meeting.CallForPaper = Announcement.NoHTMLLabel("script");
                if (meeting.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=announcementedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=metting&a=announcementedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult Attention(int meeting = -1)
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AttentionEdit(int Id, string Attention)
        {
            var meeting = new Meeting().Find(Id.ToString());
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (meeting != null)
            {
                meeting.Attention = Attention.NoHTMLLabel("script");
                if (meeting.PostModify() != null)
                {
                    return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=attentionedit&s=1{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
                }
            }
            return Redirect(String.Format("/WorkSpace/Home/ServerMessage?c=meeting&a=attentionedit&s=0{0}", user.SystemRole == UserRole.Admin ? "&journal=" + Id : ""));
        }
        public ActionResult News(int page = 0)
        {
            Meeting meeting = ViewBag.Meeting;
            var data = new ItemListBox<News>(CommonBiz.GetAllNews(NewsType.MeetingNews,
                 meeting.Id, OrganizationType.Meeting, page, 20));
            data.BuildPage(CommonBiz.GetAllNewsForPage(meeting.Id, OrganizationType.Meeting, NewsType.MeetingNews),
                page,
                20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });
            ViewBag.News = data;
            return View();
        }
        public ActionResult AddNews()
        {
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddNews( string Title, string DisplayEditor, string Form, string Content)
        {
            Meeting meeting = ViewBag.Meeting;
            CommonBiz.SaveNews(new News()
            {
                Content = Content.NoHTMLLabel("script"),
                CreateDate = DateTime.Now,
                DisplayEditor = DisplayEditor,
                Editor = HttpContext.User.Identity.Name,
                Form = Form,
                Type = NewsType.MeetingNews,
                Title = Title,
                OrgId = meeting.Id,
                OrgType = OrganizationType.Meeting
            });
            return Redirect("/WorkSpace/meeting/News");
        }
        public ActionResult NewsEdit(int Id)
        {
            ViewBag.Data = new News().Find(Id.ToString());
            return View();
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult NewsEdit(int Id, string Title, string DisplayEditor, string Form, string Content)
        {
            var data = new News().Find(Id.ToString());
            if (data != null)
            {
                data.Title = Title;
                data.DisplayEditor = DisplayEditor;
                data.Form = Form;
                data.Content = Content.NoHTMLLabel("script");
                data.PostModify();
            }
            return Redirect("/WorkSpace/meeting/News");
        }
        public ActionResult NewsCancel(int id)
        {
            CommonBiz.DeleteNews(id);
            return Redirect("/WorkSpace/meeting/News");
        }
        public ActionResult Pan()
        {
            Meeting meeting = ViewBag.Meeting;
            List<ImportantPan> pan = new ImportantPan().FindAll(
                c => c.meetingId == meeting.Id, c => c.Id, 0, 20);
            ViewBag.Pan = pan;
            return View();
        }
        public ActionResult AddPan()
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddPan(string title,string time)
        {
            Meeting meeting = ViewBag.Meeting;
            CommonBiz.NewImportantPan(new ImportantPan()
            {
                CreateDate = DateTime.Now,
                meetingId = meeting.Id,
                PanDate = DateTime.Parse(time),
                Title = title
            });
            return RedirectToAction("Pan");
        }
        public ActionResult deletePan(int id)
        {
            Meeting meeting = ViewBag.Meeting;
            var pan = new ImportantPan().Find(id.ToString());
            if (pan!= null && meeting.Id == pan.meetingId)
            {
                pan.PostDelete();
            }
            return RedirectToAction("Pan");
        }
        public ActionResult Download(int page = 0)
        {
            Meeting meeting = ViewBag.Meeting;
            var data = new ItemListBox<Download>(CommonBiz.GetAllDownloadFile(
                DownloadType.MeetingFile,OrganizationType.Meeting,meeting.Id, page, 20));
            data.BuildPage(CommonBiz.GetAllDownloadFileForPage(DownloadType.MeetingFile,
                 OrganizationType.Meeting, meeting.Id),
                page,
                20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });
            ViewBag.News = data;
            return View();
        }
        public ActionResult AddDownloadFile()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddDownloadFile(string title, string remark)
        {
            Meeting meeting = ViewBag.Meeting;
            CommonBiz.SaveDownloadFile(meeting.Id, OrganizationType.Meeting, title, remark.Replace("\r\n","<br/>"),
                 DownloadType.MeetingFile, meeting.Name, "file");
            return Redirect("/WorkSpace/meeting/Download");
        }
        public ActionResult DownloadFileEdit(int id)
        {
            Meeting meeting = ViewBag.Meeting;
            var file = new Download().Find(id.ToString());
            if (file == null || file.OrgId != meeting.Id)
            {
                return Redirect("/WorkSpace/meeting/Download");
            }
            ViewBag.DownloadFile = file;
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult DownloadFileEdit(int id, string title, string remark)
        {
            Meeting meeting = ViewBag.Meeting;
            CommonBiz.EditDownloadFile(id, title, remark.Replace("\r\n", "<br/>"), meeting.Name, "file");
            return Redirect("/WorkSpace/meeting/Download");
        }
        public ActionResult DownloadFileCancel(int id)
        {
            CommonBiz.DeleteDownloadFile(id);
            return Redirect("/WorkSpace/meeting/Download");
        }
        #endregion
    }
}